package com.nowcoder.community.controller;

import com.nowcoder.community.contant.Topic;
import com.nowcoder.community.entity.Event;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.property.QiniuProperty;
import com.nowcoder.community.utils.CommunityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import static java.nio.file.StandardOpenOption.READ;

/**
 * 分享长图视图
 * */
@Controller
@RequestMapping("/share")
@Slf4j
public class ShareController {

    @Value("${community.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${wk.image.storage}")
    private String storage;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private QiniuProperty qiniuProperty;

    /**
     * 生成长图
     * */
    @GetMapping
    @ResponseBody
    public String share(String url){
        String filename = CommunityUtils.generateUUID();
        // 触发事件：使用 wkhtmltopdf 将网页转为图片
        Event event = new Event()
                .setTopic(Topic.SHARE)
                .setData("url", url)
                .setData("filename", filename)
                .setData("suffix", "png");
        eventProducer.fireEvent(event);

        // 返回获取图片的URL
//        String imageUrl = domain + contextPath + "/share/image/" + filename; // 图片保存到本地服务器
        String imageUrl = qiniuProperty.getShare().getBucketUrl() + "/" + filename; // 图片保存到七牛云
        Map<String, Object> map = new HashMap<>();
        map.put("imageUrl", imageUrl);
        return CommunityUtils.getJsonString(200, null, map);
    }


    /**
     * 废弃：重构后图片已经上传到七牛云
     * 获取长图
     * */
    @Deprecated
    @GetMapping("/image/{filename}")
    public void image(@PathVariable String filename, HttpServletResponse response){
        if (StringUtils.isBlank(filename))
            throw new IllegalArgumentException("文件名不能为空");

        Path path = Paths.get(storage + "/" + filename + ".png");
        response.setContentType("image/png");
        try(
                ServletOutputStream out = response.getOutputStream();
                InputStream in = Files.newInputStream(path, READ)
        ) {
            Files.copy(path, out);
        } catch (IOException e) {
            log.error("获取长图失败：" + e.getMessage());
        }
    }
}
